package networking;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.ArrayList;


public class ClientThread implements Runnable 
{
	private Socket socket;
	private ArrayList<ClientThread> clients;
	ObjectInputStream in;
    ObjectOutputStream out;

	public ClientThread(Socket s, ArrayList<ClientThread> l) 
	{
		socket = s;
		clients = l;
		try 
		{
			in = new ObjectInputStream(socket.getInputStream());
			out = new ObjectOutputStream(socket.getOutputStream());
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

	public void run() 
	{
		System.out.println("Client has logged in.");
		System.out.println("There are " + clients.size() + " clients connected.");
        while(true)
		{
			try
			{
				int x = in.available();
				Request r = (Request)in.readObject();
				postMessage(r);
			}
			catch(Exception e)
			{
				//e.printStackTrace();
				clients.remove(this);
				System.out.println("Client Removed");
				break;
			}
		}
	    
	}

	private void postMessage(Request r) 
	{
		Response re = null;
		if(r.getType().equals("getHighScores"))
		{
			re = new Response(SnakeServer.getHighScores());
		}
		else if(r.getType().equals("addHighScore"))
		{
			SnakeServer.addHighScore(r.getScore());
			re = new Response(SnakeServer.getHighScores());
		}
		else if(r.getType().equals("addMap"))
		{
			re = new Response(SnakeServer.addMap(r.getMap()));
		}
		else if(r.getType().equals("getCustomMaps"))
		{
			re = new Response(SnakeServer.getMaps());
		}
		else if(r.getType().equals("disconnect"))
		{
			clients.remove(this);
			System.out.println("Client Removed PM");			
		}
		try 
		{
			if (re != null)
			{
				out.writeObject(re);
			}
		} 
		catch (IOException e) 
		{
			e.printStackTrace();
		}
	}

	
}
